<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>ADMIN</title>
    <link rel="stylesheet" th:href="@{/css/admin/base.css}">
    <link rel="stylesheet" th:href="@{/css/admin/app.css}">
</head>

<body>
<div class="app-page">
    <div class="app-page-header">
        <div class="page-title">
            <div class="title">角色管理</div>
        </div>
    </div>
    <div class="app-page-content">

        <div class="app-card">
            <div class="app-card-body">
                <!-- 过滤器 -->
                <div class="filter " style="display: none;" data-checkRole>
                    <!-- 选项切换 -->
                    <div class="form-item">
                        <div class="form-group">
                            <label for="">角色：</label>
                            <input type="text" placeholder="角色名" name="roleName" class="roleName">
                        </div>
                    </div>

                    <button class="z-btn z-primary" id="doFilter">查询</button>

                </div>

                <div class="z-btn-group">
                    <button data-state="4" class="j-btn-control z-btn z-default add-role z-hide" data-addRole>新建角色</button>
                    <button data-state="3" class="j-btn-control z-btn z-default edit-role z-hide" data-editRole>编辑角色</button>
                    <button data-state="3" class="j-btn-control z-btn z-default del-role z-hide" data-delRole>批量删除</button>
                    <button data-state="2" class="j-btn-control z-btn z-default enable-role z-hide" data-enableRole>批量启用</button>
                    <button data-state="2" class="j-btn-control z-btn z-default disable-role z-hide" data-disableRole>批量停用</button>
                    <button data-state="2" class="j-btn-control z-btn z-default bind-acount z-hide" data-bindUser>绑定用户</button>
                </div>
            </div>
        </div>
        <div class="app-card ">
            <div class="app-card-body">
                <div class="z-table-con">
                    <table class="z-table">
                        <thead>
                        <th>
                            <input type="checkbox" class="j-checkbox-all">
                        </th>
                        <th>角色名</th>
                        <th>角色描述</th>
                        <th>状态</th>
                        <th>操作</th>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>

                    <div class="z-page z-pat">
                        <!--<span class="active">1</span>-->
                        <!--<a href="#">2</a>-->
                        <!--<a href="#">3</a>-->
                        <!--<a href="#" class="last">尾页</a>-->
                        <!--<a href="#" class="next">下一页</a>-->
                    </div>
                </div>
            </div>
        </div>

    </div>


</div>

<!-- 操作面板 -->
<div class="popup-default z-popup z-fixed z-df z-flex-cc z-hide">
    <div class="bg" data-popup-close></div>
    <!--添加角色 -->
    <div class="popup-add-role section z-hide">
        <div class="title">添加角色</div>
        <div class="content">
            <form id="roleForm">
                <div class="form-item z-hide">
                    <div class="label">
                        <label>角色ID</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" class="roleId" name="roleId">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>角色名称</label>
                    </div>
                    <div class="body">
                        <input type="text" value="" placeholder="请输入角色名称" class="roleName" name="roleName" data-name="角色名称" data-rule="required,length" minlength="2" maxlength="32">
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>角色描述</label>
                    </div>
                    <div class="body upload" data-limit="0" data-input-name="">
                        <textarea placeholder="最多输入100字" class="roleDesc" name="roleDesc" data-name="角色描述" data-rule="length" minlength="2" maxlength="255"></textarea>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>角色权限</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="">
                        <input type="text" value="" disabled="disabled" class="authorityIds z-hide" name="authorityIds" data-name="角色权限">
                        <input type="text" value="" disabled="disabled" class="authorityNames" name="authorityNames">
                        <button class="z-btn z-default select-btn select-auth">选择</button>
                    </div>
                </div>

            </form>
            <div class="z-btn-group">
                <a class="btn-sub z-btn z-primary role-confirm">确定</a>
                <a class="z-btn z-default" data-popup-close>取消</a>
            </div>
        </div>
    </div>
    <!--绑定用户 -->
    <div class="popup-bind-acount section z-hide">
        <div class="title">绑定用户</div>
        <div class="content">
            <form id="bindUserForm">

                <div class="form-item z-hide">
                    <div class="label">
                        <label>角色Id</label>
                    </div>
                    <div class="body">
                        <input type="text" class="roleId"></input>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>角色名称</label>
                    </div>
                    <div class="body">
                        <p class="form-control-static roleName"></p>
                    </div>
                </div>
                <div class="form-item row">
                    <div class="label">
                        <label>添加用户</label>
                    </div>
                    <div class="body" data-limit="0" data-input-name="">
                        <input type="text" value="" disabled="disabled" class="roleBindUser" data-name="用户" data-rule="required">
                        <button class="z-btn z-default select-btn select-user">选择</button>
                    </div>
                </div>
            </form>
            <div class="z-btn-group">
                <a class="btn-sub z-btn z-primary bind-confirm">确定</a>
                <a class="z-btn z-default" data-popup-close>取消</a>
            </div>
        </div>
    </div>
</div>
<script th:src="@{/lib/jquery.min.js}"></script>
<script th:src="@{/lib/layer-v3.1.1/layer/layer.js}"></script>
<script th:src="@{/js/popup.js}"></script>
<script th:src="@{/js/admin/app.js}"></script>
<script th:src="@{/js/pagination.js}"></script>
<script th:src="@{/js/form.js}"></script>
<script>

    var rolePanelPicker = '.popup-add-role',
        bindPanelPicker = '.popup-bind-acount',
        roleData = null,
        optType = 1;
    var zTable = null;
    var pageParams = {
        roleName: '',
    };

    var auth = {
        addRole: false,
        delRole: false,
        editRole: false,
        checkRole: false,
        bindRole: false,
        enableRole: false,
        disableRole: false
    };

    $(function () {


        pageParams = $.extend(true, pageParams, App.pageParams);

        //初始化按钮显示
        auth = $.extend(true, auth, App.initBtnView(top.authBtns || []));


        if (auth['checkRole']) {
            // 获取角色列表
            initTable();
        } else {
            // 是否查看用户信息
            $('.z-table').html('抱歉，您现在没有查看角色的权限');
        }

        eventListen();
    });

    function eventListen() {
        $('#doFilter').click(function () {
            zTable.resetPage();
            zTable.reload();
        });

        $('.enable-role, .disable-role, .del-role').click(function () {

            // 检查选取数量
            var checkResult = App.checkTableSelect('mutil');
            if (!checkResult.result) {
                popup.tipsTop({type: 'warning', msg: checkResult.msg});
                return false;
            } else {
                console.log('选择数量检测成功');
            }

            var ids = App.filterByFild(zTable.getSelectedData(), 'roleId');

            if ($(this).hasClass('enable-role')) roleOpt('enable', ids);
            if ($(this).hasClass('disable-role')) roleOpt('disable', ids);
            if ($(this).hasClass('del-role')) del(ids);

        });

        $('.select-auth').click(function (e) {
            openRoleLayer(e, $(this));
        })

        $('.select-user').click(function (e) {
            openUserLayer(e, $(this));
        })

        $('.bind-acount').click(function () {

            // 检查选取数量
            var checkResult = App.checkTableSelect();

            if (!checkResult.result) {
                popup.tipsTop({type: 'warning', msg: checkResult.msg})
                return false;
            } else {
                console.log('选择数量检测成功');
            }

            var selectData = zTable.getSelectedData()[0];
            var rolename = selectData.roleName;
            var roleid = selectData.roleId;

            App.clearForm(bindPanelPicker);

            $(bindPanelPicker).find('.roleName').html(rolename);
            $(bindPanelPicker).find('.roleId').val(roleid);

            popup.open(bindPanelPicker);
        })

        // $('.role-confirm').click(function () {
        //     confirmFun();
        // });

        $("#roleForm").form({
            submitSelector: '.role-confirm',
            msg: function (msg) {
                popup.tips(msg);
            },
            submit: function () {

                confirmFun();

            }
        });

        $("#bindUserForm").form({
            submitSelector: '.bind-confirm',
            msg: function (msg) {
                popup.tips(msg);
            },
            submit: function () {

                bindConfirmFun();

            }
        })

        // $('.bind-confirm').click(function () {
        //     bindConfirmFun();
        // });

        $('.add-role,.edit-role').click(function () {
            App.clearForm(rolePanelPicker)
            popAddRole($(this));
        });

        // 修改角色
        $('.edit-role').click(function () {

            // 检测选中的数量
            // 检查选取数量
            var checkResult = App.checkTableSelect();

            if (!checkResult.result) {
                popup.tipsTop({type: 'warning', msg: checkResult.msg});
                return false;
            } else {
                console.log('选择数量检测成功');
            }

            // todo 获取需修改的数据

            edit(zTable.getSelectedData()[0].roleId);
        });
    }

    function getData($form) {

        var data = {}


        $.each($form.eq(0).serializeArray(), function (index, field) {
            if (data[field.name]) {
                data[field.name] += "," + field.value;
            } else {
                data[field.name] = field.value;
            }
        })

        return data;
    }

    // 停用
    function roleOpt(type, id) {

        if (!id) return;

        if (confirm(type === 'disable' ? '确认是否停用' : (type === 'enable' ? '确认是否启用' : '确认是否删除'))) {

            var roleId = typeof id === 'string' ? id : id.join(',');
            var url = App.apiUrlHost + '/sysRole/batchDisableSysRole';

            switch (type) {
                case 'disable':
                    url = App.apiUrlHost + '/sysRole/batchDisableSysRole';
                    break;
                case 'enable':
                    url = App.apiUrlHost + '/sysRole/batchEnableSysRole';
                    break;
                case 'del':
                    url = App.apiUrlHost + '/sysRole/delSysRole';
                    break;
            }

            App.getData({
                url: url,
                data: {roleIds: roleId},
                dataType: 'json',
                success: function (result) {

                    if (result.code == 0) {

                        popup.tipsTop({type: 'success', msg: result.msg})

                        zTable.init();

                    } else {
                        popup.tipsTop({type: 'error', msg: result.msg})
                    }
                }
            })
        }

    }


    // 启用
    // function ableRole(id) {
    //
    //     if (!id) return;
    //
    //     if (confirm('确认是否启用')) {
    //
    //         var roleId = typeof id === 'string' ? id : id.join(',');
    //         var url = App.apiUrlHost + '/sysRole/batchEnableSysRole';
    //         App.getData({
    //             url: url,
    //             data: {roleIds: roleId},
    //             dataType: 'json',
    //             success: function (result) {
    //
    //                 if (result.code == 0) {
    //
    //                     popup.tipsTop({type: 'success', msg: result.msg})
    //                     zTable.init();
    //
    //                 } else {
    //                     popup.tipsTop({type: 'error', msg: result.msg})
    //                 }
    //             }
    //         })
    //     }
    //
    // }

    function initTable() {
        zTable = $('.z-table-con').pagination({
            $pageShowArea: $('.z-page'),
            async: {
                url: App.apiUrlHost + '/sysRole/listPage',// 请求地址
                dataType: 'json',
                type: 'POST',
                data: pageParams // 请求参数
            },
            beforAjax: function (data) {

                pageParams = $.extend(true, pageParams, App.getFilter());

                pageParams['pageNum'] = parseInt(data.start / pageParams.pageSize, 10) + 1;
                return pageParams;
            },
            columns: [
                {
                    className: 'j-checkbox-col',
                    width: '30px',
                    data: null,
                    render: function (data, type, row, meta) {
                        return '<input type="checkbox" class="j-checkbox" id="' + data.roleId + '">';
                    }
                },
                {'data': 'roleName', className: 'ellipsis'},
                {'data': 'roleDesc', className: 'ellipsis'},
                {'data': 'status', className: 'ellipsis'},
                {'data': 'status', className: 'ellipsis'}
            ],
            beforeCreateRow: function ($row, data, index) {

                if (data.status) {
                    $('td', $row).eq(3).addClass('green').html('启用');
                } else {
                    $('td', $row).eq(3).addClass('maroon').html('禁用');
                }

                // $('td', $row).eq(4).html('<a href="#" classs="edit-acount" onclick="javascript:edit(' + data.roleId + ')">编辑</a><a href="#" onclick="javascript:del(this)">删除</a>');
                var optHtml = '';

                if (auth['editRole']) {
                    optHtml += '<a href="#" classs="edit-acount" onclick="javascript:edit(\'' + data.roleId + '\')">编辑</a>';
                }
                if (auth['delRole']) {
                    optHtml += '<a href="#" onclick="javascript:del(\'' + data.roleId + '\')">删除</a>';
                }

                $('td', $row).eq(4).html(optHtml);

                return $row;
            },
            drawCallback: function (setting) {
                // console.log('drawCallback');
            },
            initComplete: function (setting, json) {
                // console.log('initComplete');
            },
            formartData: function (data) {
                // console.log('formartData');

                return {
                    recordsTotal: data.data.total,
                    data: data.data.list,
                    // pageIndex: data.data.pageNum
                }
            }
        });

        zTable.init();
    }

    function edit(roleId) {

        optType = 2;

        App.clearForm(rolePanelPicker);

        var url = App.apiUrlHost + '/sysRole/getById';
        // var data = {roleId: $(self).parents('tr').find('.j-checkbox').attr('id')};
        var data = {roleId: roleId};

        submitData(url, data, (result, params) => {

            roleData = result.data;
            App.fillForm(rolePanelPicker, result.data);

            if (result.data.authorityList && result.data.authorityList.length > 0) {
                var ids = [];
                var names = [];
                for (var i = 0; i < result.data.authorityList.length; i++) {
                    var item = result.data.authorityList[i];
                    ids.push(item.authorityId);
                    names.push(item.authorityName);
                }
                $(rolePanelPicker + ' .authorityIds').val(ids.join(','))
                $(rolePanelPicker + ' .authorityNames').val(names.join(','))

            }

            $(rolePanelPicker + ' .title').html('编辑角色');
        });

        popup.open(rolePanelPicker);
    }

    function del(id) {
        if (confirm('确认是否删除？')) {

            var url = App.apiUrlHost + '/sysRole/deleteSysRole';
            var params = {roleId: id};

            if (typeof id == 'object') {
                url = App.apiUrlHost + '/sysRole/batchDeleteSysRole';
                params = {roleIds: id.join(',')};
            }

            doDel(url, params, function (result) {

                popup.tipsTop({type: 'success', msg: result.msg});

                zTable.reload();
            })

        }
    }

    function doDel(url, data, callback) {
        App.getData({
            url: url,
            data: data,
            dataType: 'json',
            success: function (result) {

                if (result.code == 0 && callback && typeof callback == 'function') {
                    callback(data);
                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                }
            }
        });

    }

    function popAddRole($self) {

        App.clearForm(rolePanelPicker);

        if ($self.hasClass('edit-role')) {
            optType = 2;
        } else {
            optType = 1;
        }
        // 修改时需要检测是否有选中的节点，并初始化数据
        if (optType == 2) {

            var checked = App.checkTableSelect();

            if (!checked.result) return;

            // todo 获取需修改的数据
            var url = App.apiUrlHost + '/sysRole/getById';
            var data = {roleId: checked.inputs[0].attr('id')}

            submitData(url, data, (result, params) => {

                roleData = result.data;
                App.fillForm(rolePanelPicker, result.data);

                if (result.data.authorityList && result.data.authorityList.length > 0) {
                    var ids = [];
                    var names = [];
                    for (var i = 0; i < result.data.authorityList.length; i++) {
                        var item = result.data.authorityList[i];
                        ids.push(item.authorityId);
                        names.push(item.authorityName);
                    }
                    $(rolePanelPicker + ' .authorityIds').val(ids.join(','))
                    $(rolePanelPicker + ' .authorityNames').val(names.join(','))

                }

                $(rolePanelPicker + ' .title').html('编辑角色');
                // $('.parentId').val(checkResult[0].pId);
            });

            popup.open(rolePanelPicker);


        } else {
            $(rolePanelPicker + ' .title').html('添加角色');
            popup.open(rolePanelPicker);
        }

    }

    function confirmFun() {
        var formData = getData($("#roleForm"));

        // 数据整合
        var data = {
            sysRoleJson: JSON.stringify(formData),
            authorityIds: $(rolePanelPicker + ' [name=authorityIds]').val()
        };
        var url = '';

        // 添加
        if (optType == 1) {

            url = App.apiUrlHost + '/sysRole/saveSysRole';

            submitData(url, data, (result) => {

                popup.close(rolePanelPicker);
                popup.tipsTop({type: 'success', msg: result.msg})
                zTable.reload();
            });
        } else {
            url = App.apiUrlHost + '/sysRole/updateSysRole';

            roleData['roleName'] = $(rolePanelPicker + ' [name=roleName]').val();
            roleData['roleDesc'] = $(rolePanelPicker + ' [name=roleDesc]').val();

            data.sysRoleJson = JSON.stringify(roleData);

            // 修改
            submitData(url, data, (result) => {

                popup.close(rolePanelPicker);

                popup.tipsTop({type: 'success', msg: result.msg})

                zTable.reload();
            });

        }
    }

    function bindConfirmFun() {

        var url = App.apiUrlHost + '/sysRole/saveUserForRole';
        var data = {
            roleId: $(bindPanelPicker).find('.roleId').val(),
            userIds: $(bindPanelPicker).find('.roleBindUser').val()
        };
        App.getData({
            url: url,
            data: data,
            success: function (result) {

                if (result.code == 0) {

                    popup.close(bindPanelPicker);
                    popup.tipsTop({type: 'success', msg: result.msg});
                } else {
                    popup.tipsTop({type: 'error', msg: result.msg});
                }
            }
        })
    }

    // 提交角色信息
    function submitData(url, data, callback) {

        App.getData({
            url: url,
            data: data,
            success: function (result) {

                if (result.code == 0 && callback && typeof callback == 'function') {
                    callback(result, data);
                } else {
                    popup.tipsTop({type: 'error', msg: result.msg})
                }
            }
        })
    }

    function openRoleLayer(e, $self) {
        e.preventDefault();
        layerOpen({
            type: 1,
            title: '选择权限',
            url: './selectAuth.html?roleId=' + $(rolePanelPicker + ' .roleId').val(),
            comfirm: (index, layero, layer) => {

                var $ids = $(layero.find('iframe')).contents().find(".src-ids");
                var $names = $(layero.find('iframe')).contents().find(".src-names");

                var idshtml = $ids.html().replace(/\<br\>/g, ',');
                var namehtml = $names.html().replace(/\<br\>/g, ',');
                // alert('选取的角色id为：' + html);
                $self.siblings('.authorityIds').val(idshtml);
                $self.siblings('.authorityNames').val(namehtml);

                layer.close(index);
            },
            cancel: (index, layero, layer) => {

                layer.close(index);
            }
        })
    }

    function openUserLayer(e, $self) {
        e.preventDefault();
        layerOpen({
            type: 1,
            title: '选择用户',
            url: './selectUser.html',
            comfirm: (index, layero, layer) => {

                var $ids = $(layero.find('iframe')).contents().find(".src-ids");

                var html = $ids.html().replace(/\<br\>/g, ',');
                // alert('选取的角色id为：' + html);
                $self.siblings('input').val(html);

                layer.close(index);
            },
            cancel: (index, layero, layer) => {

                layer.close(index);
            }
        })
    }

</script>
</body>

</html>